package com.zlp.netty.component;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;

import static io.netty.buffer.ByteBufUtil.appendPrettyHexDump;
import static io.netty.util.internal.StringUtil.NEWLINE;

/**
 * @author: zhulaiping
 * @time: 2022/9/4 21:39
 */
public class NettyBufDemo {

    public static void main(String[] args) {
        ByteBuf buf = ByteBufAllocator.DEFAULT.buffer();
        log(buf);
        buf.writeBytes("aaaaaaaaaaaaaaaaa".getBytes());
        log(buf);
        //通过该方法创建的ByteBuf是基于直接内存的ByteBuf，等同于directBuffer()
        ByteBuf buffer1 = ByteBufAllocator.DEFAULT.buffer(16);
        //class io.netty.buffer.PooledUnsafeDirectByteBuf
        System.out.println(buffer1.getClass());
        //创建池化基于堆的 ByteBuf
        ByteBuf buffer2 = ByteBufAllocator.DEFAULT.heapBuffer(16);
        //class io.netty.buffer.PooledUnsafeHeapByteBuf
        System.out.println(buffer2.getClass());
        //创建池化基于直接内存的 ByteBuf
        ByteBuf buffer3 = ByteBufAllocator.DEFAULT.directBuffer(16);
        //class io.netty.buffer.PooledUnsafeDirectByteBuf
        System.out.println(buffer3.getClass());
    }

    private static void log(ByteBuf buffer) {
        int length = buffer.readableBytes();
        int rows = length / 16 + (length % 15 == 0 ? 0 : 1) + 4;
        StringBuilder buf = new StringBuilder(rows * 80 * 2)
                .append("read index:").append(buffer.readerIndex())
                .append(" write index:").append(buffer.writerIndex())
                .append(" capacity:").append(buffer.capacity())
                .append(NEWLINE);
        appendPrettyHexDump(buf, buffer);
        System.out.println(buf.toString());
    }
}
